package com.code.common.spring;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 加载spring配置文件，提供getBean接口.
 * 
 */
public class BeanLocator {

	private static final Logger logger = Logger.getLogger(BeanLocator.class);

	private static BeanLocator instance = null;

	private ApplicationContext applicationContext = null;

	public static BeanLocator getInstance() {
		return instance;
	}

	public static BeanLocator getInstance(ServletContext sc) {
		if (instance == null){
			instance = new BeanLocator(sc);
		}
		return instance;
	}

	private BeanLocator(ServletContext sc) {
		this.loadSpring(sc);
	}

	public void reloadSpring(ServletContext sc) {
		this.loadSpring(sc);
	}

	private void loadSpring(ServletContext sc) {
		try {
			this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		} catch (Exception e) {
			logger.error("初始化spring配置文件时发生异常:" + e.getMessage(), e);
			throw new RuntimeException("初始化spring配置文件时发生异常:" + e.getMessage(), e);
		}
	}

	public Object getBean(String beanName) {
		return this.applicationContext.getBean(beanName);
	}

}